package com.clas.liu.myapplication.view.activity.impl;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clas.liu.myapplication.MyApplication;
import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.model.entity.user.UserRoot;
import com.clas.liu.myapplication.presenter.impl.BasePresenter;
import com.clas.liu.myapplication.presenter.impl.LoginPresenter;
import com.clas.liu.myapplication.view.activity.i.ILoginActivity;
import com.clas.liu.myapplication.view.util.PopupMenuUtil;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.clas.liu.myapplication.view.util.StringUtil;
import com.clas.liu.myapplication.view.widget.CircleImageView;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.squareup.picasso.Picasso;

import org.w3c.dom.Text;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by liu on 2019/3/5.
 */

public class LoginActivity extends BaseActivity<LoginPresenter> implements View.OnClickListener, ILoginActivity {

    private EditText usernameEt;
    private EditText passwordEt;
    private Button loginBt;
    private TextView forgetPd;
    private TextView register;
    private TextView exit;
    private TextView loginType;
    private RelativeLayout phoneLoginPwdLayout;
    private RelativeLayout pwdLoginPwdLayout;
    private TextView title;
    private TextView getCodeView;
    private EditText codePasswordEt;

    private boolean isPasswordType = true;

    private CountDownTimer timer;
    private EventHandler smsHandler;
    private Dialog loadingDialog;

    private long exitTime = 0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        setStatusBarTransparent();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        findView();
        init();
        setListener();
    }

    private void init() {
        initDialog();
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCodeView.setClickable(false);
                getCodeView.setTextColor(getResources().getColor(R.color.font_grey));
                String text = "重发" + "(" + String.valueOf(millisUntilFinished / 1000) + "s)";
                getCodeView.setText(text);
            }

            @Override
            public void onFinish() {
                getCodeView.setClickable(true);
                getCodeView.setText("发送验证码");
                getCodeView.setTextColor(getResources().getColor(R.color.login_blue));
            }
        };
        smsHandler = new EventHandler() {
            @Override
            public void afterEvent(final int event, int result, Object data) {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        // TODO 处理成功得到验证码的结果
                        // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                timer.start();
                            }
                        });
                    } else {
                        // TODO 处理错误的结果
                        ((Throwable) data).printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("验证码获取异常", Toast.LENGTH_SHORT);
                            }
                        });
                    }
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        // TODO 处理验证码验证通过的结果
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mPresenter.phoneIsExited(usernameEt.getText().toString());
                            }
                        });
                    } else {
                        // TODO 处理错误的结果
                        ((Throwable) data).printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("验证码错误", Toast.LENGTH_SHORT);
                                loadingDialog.dismiss();
                            }
                        });
                    }
                }
            }
        };
        SMSSDK.registerEventHandler(smsHandler);
    }

    private void setListener() {
        loginBt.setOnClickListener(this);
        register.setOnClickListener(this);
        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(passwordEt.getText())) {
                    loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt));
                    loginBt.setClickable(false);
                } else {
                    if (!TextUtils.isEmpty(usernameEt.getText())) {
                        loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt_ready));
                        loginBt.setClickable(true);
                    }
                }
            }
        });
        codePasswordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(codePasswordEt.getText())) {
                    loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt));
                    loginBt.setClickable(false);
                } else {
                    if (!TextUtils.isEmpty(usernameEt.getText())) {
                        loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt_ready));
                        loginBt.setClickable(true);
                    }
                }
            }
        });
        exit.setOnClickListener(this);
        forgetPd.setOnClickListener(this);
        loginType.setOnClickListener(this);
        getCodeView.setOnClickListener(this);

    }

    private void findView() {
        usernameEt = findViewById(R.id.login_et_name);
        passwordEt = findViewById(R.id.login_et_password);
        loginBt = findViewById(R.id.login_ok_bt);
        forgetPd = findViewById(R.id.login_forget_password);
        register = findViewById(R.id.login_register);
        exit = findViewById(R.id.login_exit);
        loginType = findViewById(R.id.login_type);
        phoneLoginPwdLayout = findViewById(R.id.login_type_phone_password_layout);
        pwdLoginPwdLayout = findViewById(R.id.login_type_pwd_password_layout);
        title = findViewById(R.id.login_phone_title);
        getCodeView = findViewById(R.id.login_get_code_tv);
        codePasswordEt = findViewById(R.id.login_et_password_code);
    }

    @Override
    protected LoginPresenter getPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_ok_bt:
                startLogin();
                break;
            case R.id.login_register:
                Intent registerIntent = new Intent(this, RegisterActivity.class);
                startActivity(registerIntent);
                break;
            case R.id.login_exit:
                ((MyApplication)getApplication()).removeALLActivity_();
                break;
            case R.id.login_type:
                judgeAndDisplayPasswordEt();
                break;
            case R.id.login_forget_password:
                Intent pwdIntent = new Intent(this, EditPasswordActivity.class);
                startActivity(pwdIntent);
                break;
            case R.id.login_get_code_tv:
                getVerificationNumber();
                break;

        }
    }

    private void initDialog() {
        loadingDialog = new Dialog(this, R.style.DialogTheme);
        loadingDialog.setContentView(View.inflate(this, R.layout.dialog_layout_register, null));
        Window window = loadingDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    private void judgeAndDisplayPasswordEt() {
        if (isPasswordType) {
            pwdLoginPwdLayout.setVisibility(View.GONE);
            phoneLoginPwdLayout.setVisibility(View.VISIBLE);
            loginBt.setClickable(false);
            loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt));
            title.setText(R.string.login_title_code);
            loginType.setText(R.string.login_title_pwd);
            usernameEt.setText("");
            passwordEt.setText("");
            isPasswordType = false;
        } else {
            pwdLoginPwdLayout.setVisibility(View.VISIBLE);
            phoneLoginPwdLayout.setVisibility(View.GONE);
            loginBt.setClickable(true);
            loginBt.setBackground(getResources().getDrawable(R.drawable.shape_login_bt));
            title.setText(R.string.login_title_pwd);
            loginType.setText(R.string.login_title_code);
            codePasswordEt.setText("");
            usernameEt.setText("");
            isPasswordType = true;
        }
    }

    public void getVerificationNumber() {
        String phoneNum = usernameEt.getText().toString();
        if (StringUtil.isMobile(phoneNum)) {
            SMSSDK.getVerificationCode("86", phoneNum);
        } else {
            showToast("请输入正确格式的手机号", Toast.LENGTH_SHORT);
        }
    }

    private void startLogin() {
        loadingDialog.show();
        String phone = usernameEt.getText().toString();
        String pd;
        if (isPasswordType)
            pd = passwordEt.getText().toString();
        else
            pd = codePasswordEt.getText().toString();
        if (StringUtil.isMobile(phone)) {
            if (!pd.equals("")) {
                if (isPasswordType)
                    mPresenter.login(phone, pd);
                else
                    SMSSDK.submitVerificationCode("86", phone, pd);
                    mPresenter.phoneIsExited(phone);
            } else {
                showToast("密码不能为空！", Toast.LENGTH_SHORT);
                loadingDialog.dismiss();
            }
        } else {
            showToast("手机格式不正确！", Toast.LENGTH_SHORT);
            loadingDialog.dismiss();
        }

    }

    @Override
    public void failBecauseNetReturn(int code) {
        loadingDialog.dismiss();
        showToast(code + "，请求失败", Toast.LENGTH_SHORT);
    }

    @Override
    public void loginReturn(int code, UserRoot user) {
        if (code == 0) {
            saveUserData(user.getData());
            RegistToIm(user.getData());
        } else {
            loadingDialog.dismiss();
            showToast(user.getMessage(), Toast.LENGTH_SHORT);
        }
    }

    private void RegistToIm(final UserData user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(String.valueOf(user.getId()),"610574147");
                    loginToIm(user);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Log.i("test", "run: " +e.getErrorCode()+" "+e.getMessage());
                    if (e.getErrorCode() == 203) {
                        loginToIm(user);
                    }
                }
            }
        }).start();
    }
    private void loginToIm(final UserData user) {
        EMClient.getInstance().login(String.valueOf(user.getId()),"610574147", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }

            @Override
            public void onError(final int i, final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i==200) {
                            EMClient.getInstance().logout(true);
                            loginToIm(user);
                        }
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {
                Log.i("test", "onError: "+s);
            }
        });
    }

    private void saveUserData(UserData data) {
        SaveUtil.<UserData>saveLocal(getApplicationContext(),data,"user");
        SaveUtil.saveLoginStatus(getApplicationContext());
    }

    @Override
    public void onBackPressed() {
        // 当popupWindow 正在展示的时候 按下返回键 关闭popupWindow 否则关闭activity
        if (PopupMenuUtil.getInstance()._isShowing()) {
            PopupMenuUtil.getInstance()._rlClickAction();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序",
                        Toast.LENGTH_SHORT);
                exitTime = System.currentTimeMillis();
            } else {
                ((MyApplication)getApplication()).removeALLActivity_();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(smsHandler);
        if (loadingDialog!=null && loadingDialog.isShowing())
            loadingDialog.dismiss();
    }
}
